﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using LiveUpload.Facebook.Properties;
using System.Globalization;

namespace LiveUpload.Facebook
{
    public class LiveUploadFacebookTraceListener : TraceListener
    {
        private static readonly string LocalAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        private static readonly string TraceFolderPath = Path.Combine(LocalAppDataPath, Path.Combine("LiveUpload", "Facebook"));
        private static readonly string TraceFilename = "LiveUploadFacebook.log";

        private TextWriterTraceListener innerListener;

        public LiveUploadFacebookTraceListener()
        {
            Stream traceFileStream = GetTraceFileStream();
            if (traceFileStream != null)
            {
                innerListener = new TextWriterTraceListener(traceFileStream);
            }
        }

        private static Stream GetTraceFileStream()
        {
            Stream traceFile = null;

            try
            {
                if(!Directory.Exists(TraceFolderPath))
                {
                    Directory.CreateDirectory(TraceFolderPath);
                }

                string traceFilePath = Path.Combine(TraceFolderPath, TraceFilename);
                traceFile = File.Open(traceFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
            }
            catch (Exception)
            {
                // Nothing we can do here.
            }

            return traceFile;
        }

        public override void WriteLine(string message)
        {
            if (this.innerListener != null)
            {
                this.innerListener.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + ": " + message);
            }
        }

        public override void Write(string message)
        {
            if (this.innerListener != null)
            {
                this.innerListener.Write(message);
            }
        }
    }
}
